package repositories

import (
	"gitee.com/golanglearn/small/database"
	"gitee.com/golanglearn/small/models"
)

type SubTaskRepository interface {
	Create(t *models.SubTask) error
	FindById(uid int, tid int) (*models.SubTask, error)
	FindByTid(tid int) (*models.SubTask, error)
	FindByUid(uid int) (int, error)
	UpdateStatus(id int) error
	Delete(uis, tid int) error
}

type subtaskRepository struct {
	*database.MySQLDB
}

func NewSubTaskRepository(db *database.MySQLDB) SubTaskRepository {
	return &subtaskRepository{db}
}

func (str *subtaskRepository) Create(st *models.SubTask) error {

	stmt, err := str.DB.Prepare("INSERT INTO subtask SET t_id=?, u_id=?, created_at=?")
	if err != nil {
		return err
	}
	defer stmt.Close()
	result, err := stmt.Exec(st.TID, st.UID, st.CreatedAt.Format("20060102150405"))
	if err != nil {
		return err
	}

	stId, err := result.LastInsertId()
	if err != nil {
		return err
	}
	st.ID = int(stId)

	return nil
}

func (str *subtaskRepository) FindById(uid int, tid int) (*models.SubTask, error) {
	subtask := models.SubTask{}

	err := str.DB.QueryRow("SELECT id, t_id, u_id FROM subtask WHERE `status` = 0 AND u_id = ? AND t_id = ?", uid, tid).Scan(&subtask.ID, &subtask.TID, &subtask.UID)
	if err != nil {
		return nil, err
	}

	return &subtask, nil
}

func (str *subtaskRepository) FindByTid(tid int) (*models.SubTask, error) {
	subtask := models.SubTask{}

	err := str.DB.QueryRow("SELECT u.name executor, t.created_at FROM subtask t INNER JOIN users u ON t.u_id = u.id WHERE t.t_id = ?", tid).Scan(&subtask.Executor, &subtask.CreatedAt)
	if err != nil {
		return nil, err
	}

	return &subtask, nil
}

func (str *subtaskRepository) FindByUid(uid int) (int, error) {
	id := 0

	err := str.DB.QueryRow("SELECT id FROM subtask WHERE `status` = 0 AND u_id = ? ORDER BY created_at DESC LIMIT 0,1", uid).Scan(&id)
	return id, err
}

func (str *subtaskRepository) UpdateStatus(id int) error {
	stmt, err := str.DB.Prepare("UPDATE subtask SET `status` = 1 WHERE id = ?")
	if err != nil {
		return err
	}
	defer stmt.Close()
	_, err = stmt.Exec(id)
	if err != nil {
		return err
	}

	return nil
}

func (str *subtaskRepository) Delete(uid, tid int) error {
	stmt, err := str.DB.Prepare("DELETE FROM subtask WHERE t_id = ? AND u_id = ?")
	if err != nil {
		return err
	}
	defer stmt.Close()
	_, err = stmt.Exec(tid, uid)
	if err != nil {
		return err
	}

	return nil
}
